"""
for循环中，如果已经确定事件A发生了，还能运行A和B同时发生的语句吗？
"""
import random


# 模拟抛掷两枚独立且均匀的六面骰子
def roll_dice_forA():
    # 第一枚骰子总是返回2、4或6中的一个
    dice1 = random.choice([2, 4, 6])
    # 第二枚骰子仍然随机返回1到6之间的一个数
    dice2 = random.randint(1, 6)
    return dice1, dice2


# 计算事件A和B的概率
def calculate_probabilities(num_trials=10000):
    count_A = 0
    count_B = 0
    count_A_and_B = 0

    for _ in range(num_trials):
        dice1, dice2 = roll_dice_forA()
        if dice1 in {2, 4, 6}:  # 事件A
            count_A += 1
        if dice2 in {1, 2, 3}:  # 事件B
            count_B += 1
        if dice1 in {2, 4, 6} and dice2 in {1, 2, 3}:  # 事件A和B同时发生
            count_A_and_B += 1

    P_A = count_A / num_trials
    P_B = count_B / num_trials
    P_A_and_B = count_A_and_B / num_trials

    return P_A, P_B, P_A_and_B


# 判断事件的独立性
def check_independence(P_A, P_B, P_A_and_B):
    # 根据独立性的定义，如果 P(A ∩ B) = P(A) * P(B)
    independence = abs(P_A_and_B - P_A * P_B) < 1e-3  # 使用一个小的容差来判断是否相等
    print(f"事件A和B是否独立？ {'是' if independence else '否'}")
    print(f"P(A) = {P_A:.4f}")
    print(f"P(B) = {P_B:.4f}")
    print(f"P(A ∩ B) = P(A和B同时发生) = {P_A_and_B:.4f}")


# 主程序
if __name__ == "__main__":
    P_A, P_B, P_A_and_B = calculate_probabilities()
    check_independence(P_A, P_B, P_A_and_B)